package test;


import java.security.MessageDigest;
import java.util.Base64;
/**
 * 单项散列函数生成短 URL
 * @author 豆包LU
 * @date 2023/4/28 15:10
 */
public class ShortenURL {

    public static void main(String[] args) {
        String longURL = "http://l.cn/fgeuifeufgioeoeifgioefioewfheiofieofoe";
        String shortURL = shorten(longURL);
        System.out.println(shortURL); // 输出短URL：http://l.cn/ScW4dt
    }

    public static String shorten(String longURL) {
        try {
            // 计算MD5散列值
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] hashBytes = md.digest(longURL.getBytes("UTF-8"));

            // 对散列值进行Base64编码
            String base64Str = Base64.getUrlEncoder().encodeToString(hashBytes);

            // 截取前6个字符作为短URL的标识符
            String shortStr = base64Str.substring(0, 6);

            // 拼接短URL前缀和标识符
            String shortURL = "http://l.cn/" + shortStr;

            return shortURL;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
